from pydantic import BaseModel
from sqlalchemy.orm import relationship
from sqlalchemy import Column, Integer, String, event, DateTime
from datetime import datetime
from typing import Optional
from models.role import Role
from models.admin_user_roles import admin_user_roles
from models.base import Base
from sqlalchemy.sql import func

metadata = Base.metadata


class AdminUser(Base):
    def to_dict(self):
        return {column.name: getattr(self, column.name) for column in self.__table__.columns}

    __tablename__ = 'admin_users'
    __table_args__ = {'extend_existing': True}
    id = Column(Integer, primary_key=True, index=True)
    username = Column(String(255, 'utf8mb4_unicode_ci'), unique=True, comment='姓名')
    hashed_password = Column(String(255, 'utf8mb4_unicode_ci'), comment='哈希密码')
    email = Column(String(255, 'utf8mb4_unicode_ci'), unique=True, comment='电子邮件')
    avatar = Column(String(255, 'utf8mb4_unicode_ci'), comment='头像地址')
    status = Column(Integer, default=1, comment='0 禁用 1 正常')
    deleted_at = Column(DateTime(timezone=True), nullable=True, comment='删除时间')
    created_at = Column(DateTime, server_default=func.now(), comment='创建时间')
    updated_at = Column(DateTime, onupdate=func.now(), comment='更新时间')
    roles = relationship(Role, secondary=admin_user_roles, backref='admin_users')


@event.listens_for(AdminUser, 'before_update')
def receive_before_update(mapper, connection, target):
    target.updated_at = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M")

@event.listens_for(AdminUser, 'before_insert')
def set_created_at(mapper, connection, target):
    if not target.created_at:
        target.created_at = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M")

class AdminUserSchema(BaseModel):
    id: int
    email: str
    avatar: Optional[str] = None
    created_at: Optional[datetime] = None
    updated_at: Optional[datetime] = None
    deleted_at: Optional[datetime] = None
    username: str
    email: str
    status: int

    class Config:
        orm_mode = True
        json_encoders = {
            datetime: lambda v: v.strftime('%Y-%m-%d %H:%M:%S') if v else None
        }
        from_attributes = True
